package com.ruoyi.project.paea.paeaDsTrade.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ruoyi.common.utils.CommonParaTool;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.project.data.tradeOperate.domain.PaeaDsTradeQuery;
import com.ruoyi.project.er.domain.PaeaErError;
import com.ruoyi.project.er.service.IPaeaErErrorService;
import com.ruoyi.project.paea.paeaDsTrade.domain.PaeaDsTrade;
import com.ruoyi.project.paea.paeaDsTrade.mapper.PaeaDsTradeMapper;
import com.ruoyi.project.paea.paeaDsTrade.model.TradeTellerImagesVo;
import com.ruoyi.project.paea.paeaDsTrade.service.IPaeaDsTradeService;
import com.ruoyi.project.sdi.input.service.IInputService;
import com.ruoyi.project.sdi.sdiImage.domain.SdiImage;
import com.ruoyi.project.sdi.sdiImage.service.ISdiImageService;
import com.ruoyi.project.sdi.sdiPaeaArc.domain.SdiPaeaArc;
import com.ruoyi.project.sdi.sdiPaeaArc.service.ISdiPaeaArcService;
import com.ruoyi.project.tool.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 交易流水Service业务层处理
 *
 * @author 关晓强
 * @date 2020-03-16
 */
@Service
public class PaeaDsTradeServiceImpl extends ServiceImpl<PaeaDsTradeMapper, PaeaDsTrade> implements IPaeaDsTradeService
{
    @Autowired
    private PaeaDsTradeMapper paeaDsTradeMapper;
    @Autowired
    private ISdiImageService sdiImageService;
    @Autowired
    private ISdiPaeaArcService sdiPaeaArcService;
    @Autowired
    private IInputService iInputService;
    @Resource
    private IPaeaErErrorService paeaErErrorService;

    /**
     * 查询交易流水
     *
     * @param id 交易流水ID
     * @return 交易流水
     */
    @Override
    public PaeaDsTrade selectPaeaDsTradeById(String id)
    {
        return paeaDsTradeMapper.selectPaeaDsTradeById(id);
    }

    /**
     * 查询交易流水列表
     *
     * @param paeaDsTrade 交易流水
     * @return 交易流水
     */
    @Override
    public List<PaeaDsTrade> selectPaeaDsTradeList(PaeaDsTrade paeaDsTrade)
    {
        return paeaDsTradeMapper.selectPaeaDsTradeList(paeaDsTrade);
    }

    @Override
    public List<PaeaDsTrade> selectPaeaDsTrades(PaeaDsTradeQuery paeaDsTrade) {
        if (paeaDsTrade.getTrDate()!=null){
            paeaDsTrade.setTrDateStr(DateTimeUtil.shortFmt(paeaDsTrade.getTrDate(),"yyyy-MM-dd"));
        }
        List<PaeaDsTrade> list = paeaDsTradeMapper.selectPaeaDsTrades(paeaDsTrade);
        return list;
    }

    /**
     * 新增交易流水
     *
     * @param paeaDsTrade 交易流水
     * @return 结果
     */
    @Override
    public int insertPaeaDsTrade(PaeaDsTrade paeaDsTrade)
    {
        return paeaDsTradeMapper.insertPaeaDsTrade(paeaDsTrade);
    }

    /**
     * 修改交易流水
     *
     * @param paeaDsTrade 交易流水
     * @return 结果
     */
    @Override
    public int updatePaeaDsTrade(PaeaDsTrade paeaDsTrade)
    {
        return paeaDsTradeMapper.updatePaeaDsTrade(paeaDsTrade);
    }

    /**
     * 删除交易流水对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deletePaeaDsTradeByIds(String ids)
    {
        return paeaDsTradeMapper.deletePaeaDsTradeByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除交易流水信息
     *
     * @param id 交易流水ID
     * @return 结果
     */
    @Override
    public int deletePaeaDsTradeById(String id)
    {
        return paeaDsTradeMapper.deletePaeaDsTradeById(id);
    }

    /**
     * 回退批次时，回退流水相关信息
     * @param sdiPaeaArc
     */
    @Override
    @Transactional
    public void deleteTradeImageRelBySdiPaeaArc(SdiPaeaArc sdiPaeaArc) {
        List<PaeaDsTrade> paeaDsTrades = this.list(new QueryWrapper<PaeaDsTrade>()
                .eq("tr_date",sdiPaeaArc.getTrDate())
                .eq("br_code",sdiPaeaArc.getOrgCode())
                .eq("tr_telr",sdiPaeaArc.getTellerCode()));

            List<PaeaDsTrade> changedTrades = paeaDsTrades.stream()
                    .filter(paeaDsTrade -> StringUtils.isNotEmpty(paeaDsTrade.getImageId()))
                    .collect(Collectors.toList());

        if(changedTrades!=null && !changedTrades.isEmpty()){
            changedTrades.stream().forEach(paeaDsTrade -> {
                paeaDsTrade.setImageId(null);
                paeaDsTrade.setStatus(null);
                paeaDsTrade.setType(null);
            });

            this.updateBatchById(changedTrades);
        }
    }

    @Override
    @Transactional
    public int filterTradesByIds(String ids) {
        return paeaDsTradeMapper.filterTradesByIds(Convert.toStrArray(ids));
    }
    @Override
    @Transactional
    public int openTradesByIds(String ids) {
        return paeaDsTradeMapper.openTradesByIds(Convert.toStrArray(ids));
    }

    /**
     * 通过流水查询影像
     * @param paeaDsTrade
     * @return
     */
    public List<SdiImage> getSdiImagesByPaeaDsTrade(PaeaDsTrade paeaDsTrade) {
        java.util.Date _date =paeaDsTrade.getTrDate();
        String _imageId =paeaDsTrade.getImageId();
        String vchNo = paeaDsTrade.getVchNo();

        if (paeaDsTrade.getImageId() == null ||paeaDsTrade.getImageId().trim().length()==0) {
            //监督下发差有时同一流水号下没有影像 根据流水号再去查询一次
            //PaeaDsTrade _paeaDsTrade =this.findByVchNoAndTrDate1(paeaDsTrade.getVchNo(),paeaDsTrade.getTrDate()); 分表查询
            List<PaeaDsTrade> paeaDsTradeList = this.list(new QueryWrapper<PaeaDsTrade>()
                    .eq(vchNo!=null,"vch_No",vchNo));
            if(paeaDsTradeList==null || paeaDsTradeList.size()<0){
                return null;
            }else{
                PaeaDsTrade trade = paeaDsTradeList.get(0);
                if(trade.getImageId() == null ||trade.getImageId().trim().length()==0){
                    return null;
                }else{
                    _date = trade.getTrDate();
                    _imageId =trade.getImageId();
                }
            }
        }
       // String imageTableClassName = this.getImageTableClassName(paeaDsTrade.getTrDate()); 分表查询
//        String hql = "SELECT img FROM SdiImage img"
//                + " WHERE img.parentId = ? order by img.indexNo";
//        hql = hql.replaceAll(IMAGE_BASE_CLASS_NAME, imageTableClassName);
//        List<POJO> pojos = this.paeaDsTradeDao.find(hql, _imageId);
        List<SdiImage> sdiImageList = sdiImageService.list(new QueryWrapper<SdiImage>()
                .eq(_imageId!=null,"parent_id",_imageId));

        List<SdiImage> images = new ArrayList<SdiImage>();
        int curIndexNo = -1;
        for (SdiImage image : sdiImageList) {
            if (curIndexNo != image.getIndexNo()) {
                images.add(image);
                curIndexNo = image.getIndexNo();
            }
        }
        return images;
    }


    /**
     * 查询批次的流水列表
     * @param sdiPaeaArc
     * @return
     */
    @Override
    public List<PaeaDsTrade> getPaeaDsTradesBySdiPaeaArc(SdiPaeaArc sdiPaeaArc) {
        return this.list(new QueryWrapper<PaeaDsTrade>()
                .eq("tr_date",sdiPaeaArc.getTrDate())
                .eq("br_code",sdiPaeaArc.getOrgCode())
                .eq("tr_telr",sdiPaeaArc.getTellerCode())
                .ne("filter_flag","2")
                .orderByAsc("txn_seq")
                .orderByDesc("txn_amt"));
    }

    /**
     * 批量更新流水
     *
     * @param paeaDsTradeList
     */
    @Override
    public void batchUpdatePaeaDsTrades(List<PaeaDsTrade> paeaDsTradeList) {
        this.paeaDsTradeMapper.batchUpdatePaeaDsTrades(paeaDsTradeList);
    }

    /**
     * 查询流水柜员当日影像
     *
     * @param id
     * @return
     */
    @Override
    public TradeTellerImagesVo getTradeTellerImagesVo(String id) {
        TradeTellerImagesVo tradeTellerImagesVo = new TradeTellerImagesVo();
        //获取当前选择流水
        PaeaDsTrade paeaDsTrade = this.getById(id);
        //获取当前流水列表
        List<PaeaDsTrade> paeaDsTrades = this.list(new QueryWrapper<PaeaDsTrade>()
                .eq("tr_date",paeaDsTrade.getTrDate())
                .eq("br_code",paeaDsTrade.getBrCode())
                .eq("tr_telr",paeaDsTrade.getTrTelr())
                .eq("filter_flag","1")
                .orderByAsc("txn_seq"));
        //获取流水列表影像
        SdiPaeaArc sdiPaeaArc = this.sdiPaeaArcService.getOne(new QueryWrapper<SdiPaeaArc>()
                    .eq("tr_date",paeaDsTrade.getTrDate())
                    .eq("org_code",paeaDsTrade.getBrCode())
                    .eq("teller_code",paeaDsTrade.getTrTelr()));
        List<SdiImage> sdiImages = Lists.newArrayList();
        if(sdiPaeaArc!=null){
            sdiImages = this.sdiImageService.getSdiImagesBySdiPaeaArc(sdiPaeaArc);
            String imageUrlPrefix = CommonParaTool.getImgPathPrefix(sdiPaeaArc.getAuditOrgCode());
            tradeTellerImagesVo.setImageUrlPrefix(imageUrlPrefix);
        }
        Map<String, List<SdiImage>> sdiImageMap = iInputService.groupImagesByVchNo(sdiImages);

        //放入流水关联影像
        paeaDsTrades.stream().forEach(trade -> {
            TradeTellerImagesVo.PaeaDsTradeDetail detail = new TradeTellerImagesVo.PaeaDsTradeDetail();
            BeanUtils.copyProperties(trade,detail);
            List<SdiImage> sdiImageList = sdiImageMap.get(detail.getVchNo());
            if(StringUtils.isNotEmpty(sdiImageList)){
                detail.getSdiImageInputList().addAll(sdiImageList);
            }
            tradeTellerImagesVo.getPaeaDsTradeDetails().add(detail);
        });
        tradeTellerImagesVo.setCurrId(id);
        return tradeTellerImagesVo;
    }

    @Override
    public PaeaDsTrade selectPaeaDsTrade4Image(PaeaDsTrade trade) {
        return this.getOne(new QueryWrapper<PaeaDsTrade>().eq("tr_date",trade.getTrDate()).eq("br_code",trade.getBrCode()).eq("vch_no",trade.getVchNo()).isNotNull("image_id"));
    }


}
